//用户个人设置：交易密码/实名认证
app.controller('UserController', function($scope, $location,$ionicHistory,$ionicPopup,$ionicModal,$http,$httpParamSerializer,userService) {
  $scope.istradepwd=false;
  $scope.isauth=false;
  userService.getUserInfo(window.localStorage.memberId).then(function(result){
    //console.log('products get successed');
    if(result.code=='0'){
      if(result.member.isTradePwd=='1'){
        $scope.istradepwd = true;
      }
      if(result.member.isAuth=='1'){
        $scope.isauth=true;
      }
    } else {
      $ionicPopup.alert({title: result.msg,okText:'确定'});
    }
  },function(){
    console.log('products get error');    
  });
  $scope.new_set_trade_pwd=function(){
    $scope.istradepwd = false;
  }
  $scope.new_set_auth=function(){
    $scope.isauth = false;
  }  

  $scope.trpwd="";   
  $scope.num={"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":0,"k":".","l":"C"};  
  $scope.doInput=function(n){    
    if ($scope.pwdlenght == 6 && n!="C") return false;    
    if(n=="C"){//清除键  
      $scope.trpwd= $scope.trpwd.slice(0,-1);     
    }else {
      $scope.trpwd=$scope.trpwd+""+n; 
    }         
    $scope.pwdlenght = $scope.trpwd.length; 
  };


  $ionicModal.fromTemplateUrl('templates/pay/numberkeyboard.html', {  
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {  
    $scope.modalNumberKeyboard = modal;  
  });  
  var currentInput;
  $scope.showKeyBoard = function(t){    
    $scope.modalNumberKeyboard.show();  
    var emodal = document.getElementsByClassName('keyboard')[0];
    angular.element(emodal.parentNode.parentNode).addClass('numberkeyboard');
    currentInput=t;  
  };
  $scope.finishInput = function(){  
    eval('$scope.'+currentInput+'=$scope.trpwd==""?"0":$scope.trpwd;');  
    $scope.modalNumberKeyboard.hide();  
  }

  $scope.settradepwd = function(type){
    console.log(type);
    if (type== 'pwd'){
      $scope.tradePwd = $scope.trpwd;
      $scope.trpwd="";
      $scope.pwdlenght = 0;
      $scope.popuptwd.close();
      $scope.modalNumberKeyboard.hide();
      return ;
    }
    if (type == 'repwd' && $scope.tradePwd == $scope.trpwd){
      $scope.reTradePwd = $scope.trpwd;
      $scope.trpwd = '';
      $scope.pwdlenght = 0;//清空
      $scope.popuptwd.close();
      $scope.modalNumberKeyboard.hide();
      return ;
    }
    if(type == 'repwd' && $scope.tradePwd != $scope.trpwd){
      $scope.trpwd = '';
      $scope.pwdlenght = 0;//清空
      $scope.popuptwd.close();
      $scope.modalNumberKeyboard.hide();
      $ionicPopup.alert({title: '2次交易密码不一致',okText:'确定'})
    }
  }

  $scope.openkeyboard=function(){
    $scope.trpwd = '';
    $scope.pwdlenght = 0;//清空
    $scope.pwdtype = 'pwd';
    $scope.settitle = '设置金法宝交易密码';
    $scope.popuptwd = $ionicPopup.show({
      templateUrl: 'settradepwd.html',
      scope: $scope,
      cssClass: 'tradepwd'
    });

    $scope.showKeyBoard();
  }  
  $scope.reopenkeyboard=function(){
    $scope.trpwd = '';
    $scope.pwdlenght = 0;//清空
    $scope.pwdtype = 'repwd';  
    $scope.settitle = '确认金法宝交易密码';
    $scope.popuptwd = $ionicPopup.show({
      templateUrl: 'settradepwd.html',
      scope: $scope,
      cssClass: 'tradepwd'
    });/*,
      buttons: [
        { text: '取消' },
        {
          text: '确定',
          type: 'button-positive',
          onTap: function(e) {
            console.log(e);
          }
        }
      ]        

    $scope.popuptwd.then(function(res) {
     console.log('Tapped!', res);
    });*/
    $scope.showKeyBoard();
  }  

  $scope.shownumberkeyboard = function(){
    $scope.showKeyBoard();
  };
  $scope.canceltwd = function(){
    $scope.popuptwd.close();
    $scope.modalNumberKeyboard.hide(); 
  };
  $scope.$on('$destroy', function() {
    $scope.modalNumberKeyboard.remove();//对应删除      
  });

  $scope.tpwd={
    memberId:window.localStorage.memberId,
    tradePwd:'',
    reTradePwd:'',
    loginPwd:''
  };
  $scope.confirm_modify_trade=function(){
    $scope.tpwd.tradePwd = $scope.tradePwd;
    $scope.tpwd.reTradePwd = $scope.reTradePwd;
    console.log($scope.tpwd);    
    if($scope.tpwd.loginPwd==''){
      $ionicPopup.alert({title: '登录密码不能为空',okText:'确定'});
      return;
    }
    if($scope.tpwd.tradePwd==''){
      $ionicPopup.alert({title: '交易密码不能为空',okText:'确定'});
      return;
    }
    if($scope.tpwd.reTradePwd==''){
      $ionicPopup.alert({title: '确认交易密码不能为空',okText:'确定'});
      return;
    }
    if($scope.tpwd.tradePwd.length<6){
      $ionicPopup.alert({title: '交易密码不能小于6位',okText:'确定'});
      return;
    }
    if($scope.tpwd.reTradePwd!=$scope.tpwd.tradePwd){
      $ionicPopup.alert({title: '2次交易密码不一致',okText:'确定'});
      return;
    }
    $http.get(window.localStorage.base_url+'/app/member/setTradePwd?'+$httpParamSerializer($scope.tpwd)+'&token='+window.localStorage.token).success(function(req){
      if(req.code=='0'){
        $ionicPopup.alert({title: '设置交易密码成功',okText:'确定'}).then(function(){
          if(window.localStorage.paysettradepwdback = 'paysettradepwdback'){
            window.localStorage.removeItem('paysettradepwdback');
            $ionicHistory.goBack(-2);//设置后返回交易
          }else{
            $location.path("/user/detail");
          }
        });        

      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'})
      }
    }).error(function(res){
      console.log(res);
    })
  }
  
  $scope.userAuth={
    realname:'',
    identityNumber:'',
    memberId:window.localStorage.memberId
  }
  $scope.oldRealname='';
  $http.get(window.localStorage.base_url+'/app/member/getUserInfo?memberId='+window.localStorage.memberId+'&token='+window.localStorage.token).success(function(req){
      if(req.code=='0'){
        //$scope.userAuth.realname=req.member.realname;
        //$scope.userAuth.identityNumber=req.member.identityNumber;
        $scope.oldRealname=req.member.realname;
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'})
      }
    }).error(function(res){
      console.log(res);
    })
  $scope.realnameAuth=function(){
    console.log($scope.userAuth);
    if($scope.userAuth.realname==''){
      $ionicPopup.alert({title: '真实姓名不能为空',okText:'确定'});
      return;
    }
    if($scope.userAuth.identityNumber==''){
      $ionicPopup.alert({title: '身份证号不能为空',okText:'确定'});
      return;
    }
    var exp = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/;
    if(!exp.test($scope.userAuth.identityNumber)){
      $ionicPopup.alert({title: '身份证号格式错误',okText:'确定'})
      return;
    }
    $http.post(window.localStorage.base_url+'/app/member/realnameAuth?'+$httpParamSerializer($scope.userAuth)+'&token='+window.localStorage.token).success(function(req){
      if(req.code=='0'){
        $ionicPopup.alert({title: '设置成功',okText:'确定'})
        $location.path("/user/detail");
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'})
      }
    }).error(function(res){
      console.log(res);
    })
  }
  
})

//用户首页 修改登录密码
/*by:zony 2016年3月14日20:37:33*/
.controller('UserIndexController',function($scope,$ionicPopup,$location,$ionicHistory,$http,$httpParamSerializer,userService){
  userService.getUserInfo(window.localStorage.memberId).then(function(result){
    if(result.code=='0'){
      $scope.isauth = result.member.isAuth=='1'?false:true;
      $scope.iscard = result.member.isCard=='1'?false:true;
      $scope.istradepwd = result.member.isTradePwd=='1'?false:true;
      $scope.realname = result.member.realname;
    }
  },function(){
    console.log('get userinfo error');    
  });
  $scope.pwd={
    memberId:window.localStorage.memberId,
    newPwd:'',
    reLoginPwd:'',
    loginPwd:''
  };
  //console.log(window.localStorage.isLogin);
  if(window.localStorage.isLogin=='true'){
    $scope.loginDiv=true;
    $scope.nologinDiv=false;
    $scope.phone=window.localStorage.phone;
  } else {
    $scope.loginDiv=false;
    $scope.nologinDiv=true;
  }

  if(window.localStorage.isLogin == 'true'){
  $http.get(window.localStorage.base_url+'/app/assets/getTotalAsset?memberId='+window.localStorage.memberId+'&token='+window.localStorage.token)
  .success(function(req){
    if(req.code=='0'){
      console.log(req); //总资产
      if (!req.lastIncome) {req.lastIncome=0};  //返回为空 设为0
      if (!req.periodMoney) {req.periodMoney=0};  //返回为空 设为0
      $scope.assets = req;       
    }else{
      console.log(req);
      $ionicPopup.alert({title: req.msg,okText:'确定'});
    }
  }).error(function(res){
    console.log(res);
  });
}

  $scope.logout=function(){
    $ionicPopup.confirm({
      title:'确认退出?',
      cancelText:'取消',
      okText:'确定'
    }).then(function(res){
      if(res){
        userService.setLogout();
        $location.path('/web/user/index');
      }
    })
  }
  $scope.confirm_modify=function(){
    console.log($scope.pwd);
    if($scope.pwd.loginPwd==''){
      $ionicPopup.alert({title: '原密码不能为空',okText:'确定'});
      return;
    }
    if($scope.pwd.newPwd==''){
      $ionicPopup.alert({title: '新密码不能为空',okText:'确定'});
      return;
    }
    if($scope.pwd.reLoginPwd==''){
      $ionicPopup.alert({title: '确认密码不能为空',okText:'确定'});
      return;
    }
    if($scope.pwd.newPwd.length<6){
      $ionicPopup.alert({title: '新密码不能小于6位',okText:'确定'});
      return;
    }
    if($scope.pwd.reLoginPwd!=$scope.pwd.newPwd){
      $ionicPopup.alert({title: '2次新密码不一致',okText:'确定'});
      return;
    }
    $http.get(window.localStorage.base_url+'/app/member/modifyPwd?'+$httpParamSerializer($scope.pwd)+'&token='+window.localStorage.token).success(function(req){
      if(req.code=='0'){
        userService.setLogout();
        $location.path('/web/user/index');
      }else{
        console.log(req);
        $ionicPopup.alert({
          title: req.msg,
          okText:'确定'
          })
      }
    }).error(function(res){
      console.log(res);
    })
  }
})

.controller('UserLoginController',function($scope,$http,$location,$ionicPopup,userService){
  $scope.data={
    name:'',
    pwd:'',
    rpwd:false
  };
  var inf='';
  function checkoutPWD(){
    var d=$scope.data;
    if(d.name==''){inf='用户名为6-20位';return false;}
    if(d.pwd.length<6){inf ='密码长度至少六位';return false;}
    return true;
  }
  $scope.register = function() {
    $location.path('/user/register');
  };

  $scope.confirm_register = function() {
    $location.path('/web/product/index');
  };
  $scope.submit=function(){
    console.log($scope.data);
    if(!checkoutPWD()){
      console.log(1111);
      $ionicPopup.alert({
        title: inf,
        okText:'确定'
      }).then(function(res) {
        $scope.data.pwd='';
      });
    }else{
      var z=$scope.data;
      var parm='?phone='+z.name+'&loginPwd='+z.pwd;
      $http.get(window.localStorage.base_url+'/app/member/login'+parm).success(function(req){
        if(req.code=='0'){
          if(window.localStorage){
               userService.setLogin(z.name,req.token,req.member.id);console.log(req);
               $location.path('/web/user/index');
          }else{
               alert('This browser does NOT support localStorage');
          }
        }else{
          console.log(req);
          $ionicPopup.alert({
            title: req.msg,
            okText:'确定'
            })
        }
      }).error(function(res){
        console.log(res);
      })
    }
  }
})

.controller('UserRegisterController',function($scope,$http,$ionicPopup,$location,userService,$timeout){
  $scope.reg={
    phone:'',
    loginPwd:'',
    reLoginPwd:'',
    validateCode:'',
    inviteCode:''
  }
  var inf='';
  function check(){
    var a=$scope.reg;
    if(!/^1\d{10}$/.exec(a.phone)){
      inf='请检查手机号输入格式';
      return false;
    }
    if(a.loginPwd.length<6||a.loginPwd.length>20){
      inf='密码长度为6-20位';
      return false;
    }
    if(a.loginPwd != a.reLoginPwd){
      inf='两次密码不一致';
      return false;
    }
    return true;
  }
  $scope.fetchButton=true;
  $scope.isValidPhone=function(){
    if(/^1\d{10}$/.test($scope.reg.phone)){
      $scope.fetchButton=false;
    }else{
      $scope.fetchButton=true;
    }
  }
  $scope.registe=function(){
    //console.log($scope.reg);
    if(check()){
      var data=$scope.reg,z=$scope.reg;
      var parm='?phone='+z.phone+'&loginPwd='+z.loginPwd+'&reLoginPwd='+z.reLoginPwd+'&validateCode='+z.validateCode+'&inviteCode='+z.inviteCode;
      $http.get(window.localStorage.base_url+'/app/member/register'+parm).success(function(req){
        if(req.code=='0'){
          if(window.localStorage){
               userService.setLogin(z.phone,req.token,req.member.id);
               if(req.discountDesc!=null){
                  $ionicPopup.alert({title: req.discountDesc, okText:'确定'})
               }
               $location.path('/web/user/index');
          }else{
               alert('This browser does NOT support localStorage');
          }
        }else{
          $ionicPopup.alert({
            title: req.msg,
            okText:'确定'
            })
        }
      }).error(function(res){
        console.log(res);
      })
    }else{
      $ionicPopup.alert({
        title: inf,
        okText:'确定'
      }).then(function(res) {
        
      });
    }
  }
  $scope.buttonText="获取";
  var countdown=60;
  $scope.sendCode=function(){
    $http.get(window.localStorage.base_url+'/app/member/getVerifyCode?phone='+$scope.reg.phone).success(function(req){
      if(req.code=='0'){
        settime();
      }else{
        $ionicPopup.alert({
          title: req.msg,
          okText:'确定'
          })
      }
    }).error(function(res){
      console.log(res);
    })
  }
  function settime() { 
    if (countdown == 0) { 
      $scope.fetchButton=false;
      $scope.buttonText="获取"; 
      countdown = 60; 
    } else { 
      $scope.fetchButton=true;
      $scope.buttonText="重试(" + countdown + ")";
      countdown--; 
      $timeout(function() { 
      settime() 
      },1000) 
    } 
  } 
})

.controller('UserPasswordController',function($scope,$http,$ionicPopup,$location,userService,$timeout){
  $scope.reset={
    phone:'',
    loginPwd:'',
    reLoginPwd:'',
    validateCode:''
  }
  var inf='';
  function check(){
    var a=$scope.reset;
    if(!/^1\d{10}$/.exec(a.phone)){
      inf='请检查手机号输入格式';
      return false;
    }
    if(a.loginPwd.length<6||a.loginPwd.length>20){
      inf='密码长度为6-20位';
      return false;
    }
    if(a.loginPwd != a.reLoginPwd){
      inf='两次密码不一致';
      return false;
    }
    return true;
  }
  $scope.fetchButton=true;
  $scope.isValidPhone=function(){
    if(/^1\d{10}$/.test($scope.reset.phone)){
      $scope.fetchButton=false;
    }else{
      $scope.fetchButton=true;
    }
  }
  $scope.resetpwd=function(){
    if(!/^1\d{10}$/.exec($scope.reset.phone)){
      inf='请检查手机号输入格式';
      return false;
    }
    console.log($scope.reset);
    if(check()){
      var z=$scope.reset;
      var parm='?phone='+z.phone+'&loginPwd='+z.loginPwd+'&reLoginPwd='+z.reLoginPwd+'&validateCode='+z.validateCode;
      $http.get(window.localStorage.base_url+'/app/member/validateCodeForgetPwd'+parm).success(function(req){
        if(req.code=='0'){
                $ionicPopup.alert({
                  title: '重置密码成功！',
                  okText:'确定'
                }).then(function(res) {
                  var topage = window.localStorage.loginx;
                  if (topage == "topay" || topage == "totzfx" || topage == "tofeedback"){
                    $ionicHistory.goBack();//立即提交遇未登录情形?todo重置密码返回
                  }else{
                    $location.path('/user/login');                    
                  }
                });
        }else{
          $ionicPopup.alert({
            title: req.msg,
            okText:'确定'
            })
        }
      }).error(function(res){
        console.log(res);
      })
    }else{
      $ionicPopup.alert({
        title: inf,
        okText:'确定'
      }).then(function(res) {
        
      });
    }
  }
  $scope.buttonText="获取";
  var countdown=60;
  $scope.sendCode=function(){
    console.log($scope.reset.phone);
    $http.get(window.localStorage.base_url+'/app/member/getVerifyCodeForgetPwd?phone='+$scope.reset.phone).success(function(req){
      if(req.code=='0'){
        settime();
      }else{
        $ionicPopup.alert({
          title: req.msg,
          okText:'确定'
          })
      }
    }).error(function(res){
      console.log(res);
    })
  }
  function settime() { 
    if (countdown == 0) { 
      $scope.fetchButton=false;
      $scope.buttonText="获取"; 
      countdown = 60; 
    } else { 
      $scope.fetchButton=true;
      $scope.buttonText="重试(" + countdown + ")";
      countdown--; 
      $timeout(function() { 
      settime() 
      },1000) 
    } 
  } 
})

.controller('UserInviteController',function($scope,$http,$ionicPopup,$location,userService,$timeout){
})